/*
 * @Copyright (c) 2018 缪聪(mcg-helper@qq.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");  
 * you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *     
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *     
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.
 */

package com.mcgrobot.controller.user;

import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mcgrobot.common.Constants;
import com.mcgrobot.controller.base.BaseController;
import com.mcgrobot.entity.auth.McgUser;
import com.mcgrobot.entity.common.McgResult;
import com.mcgrobot.plugin.endesign.RSAEncrypt;
import com.mcgrobot.service.UserService;
import com.mcgrobot.util.PageData;

@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/index")
	public ModelAndView index() throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("user/index");
		mv.addObject("version", Constants.VERSION);
		return mv;
	}
	
    @RequestMapping(value="getUserList", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult getUserList() throws ClassNotFoundException, IOException {
    	
    	McgResult mcgResult = new McgResult();
    	List<McgUser> mcgUserList = userService.getUserList();
    	mcgResult.getResultMap().put("dataList", mcgUserList);
    	return mcgResult;
    }
    
    @RequestMapping(value="getUser", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult getUser(String account) {
        
        McgResult mcgResult = new McgResult();
		try {
	        if(!StringUtils.isEmpty(account)) {
	        	McgUser mcgUser = userService.selectByPrimaryKey(account);
	        	mcgResult.getResultMap().put("mcgUser", mcgUser);
	        }
		} catch (Exception e) {
			mcgResult.setStatusCode(0);
			mcgResult.setStatusMes("获取用户信息失败，请重试！");
			logger.error("根据UserId获取用户信息失败：", e);
		}
        return mcgResult;
    }
    
	@RequestMapping(value="/initCreateUserModal")
	public ModelAndView initCreateUserModal() throws Exception {
		ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.addObject("modalId", pd.get("modalId"));
		mv.setViewName("user/initCreateUserModal");
		return mv;
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public McgResult taskSave(@RequestBody McgUser mcgUser) {
		McgResult mcgResult = new McgResult();
		try {
			if (StringUtils.isEmpty(mcgUser.getUserName())) {
				mcgResult.setStatusCode(0);
				mcgResult.setStatusMes("请填写用户名称！");
				return mcgResult;
			}
			if (StringUtils.isEmpty(mcgUser.getAccount()) ) {
				mcgResult.setStatusCode(0);
				mcgResult.setStatusMes("请填写登录帐号！");
				return mcgResult;
			}
			if (StringUtils.isEmpty(mcgUser.getPwd()) ) {
				mcgResult.setStatusCode(0);
				mcgResult.setStatusMes("请填写登录密码！");
				return mcgResult;
			}
			if (StringUtils.isEmpty(mcgUser.getRoleType()) ) {
				mcgResult.setStatusCode(0);
				mcgResult.setStatusMes("请选择角色类型！");
				return mcgResult;
			}
			
			String pwd = RSAEncrypt.segmentDecrypt(mcgUser.getPwd());
			if(!StringUtils.isEmpty(pwd)) {
				mcgUser.setPwd(DigestUtils.md5DigestAsHex(pwd.getBytes(Constants.CHARSET)));
			}
			if(StringUtils.isEmpty(mcgUser.getUserId())) {
				mcgResult.setStatusCode(userService.insertSelective(mcgUser));
			} else {
				mcgResult.setStatusCode(userService.updateByPrimaryKeySelective(mcgUser));
			}
			
		} catch (Exception e) {
			mcgResult.setStatusCode(0);
			mcgResult.setStatusMes("保存用户失败，请重试！");
			logger.error("保存用户失败：", e);
		}
		
		return mcgResult;
	}
	
    @RequestMapping(value="userDelete", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public McgResult userDelete(String account) {
    	McgResult mcgResult = new McgResult();
    	mcgResult.setStatusCode(userService.deleteByPrimaryKey(account));
    	
    	return mcgResult;
    }
	
}
